<template>
    <div>
        <el-select @change="onDbSelectChange" style="width: 30%;" v-model="query.Id" placeholder="请选择">
            <el-option v-for="item in dbOptions" :label="item.Name" :value="item.Id">
            </el-option>
        </el-select>
    </div>
    <el-table v-loading="isLoading" height="800px" :show-overflow-tooltip="true" :data="tableData">
        <!-- <el-table-column v-for="item in bgcolumnNames" :prop="item.Name" :label="item.label" /> -->
        <el-table-column v-for="item in bgcolumnNames" :prop="item.Name" :label="item.Name">
            <template #default="{ row }">
                <span>{{ row.Name }}</span>
            </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作">
            <template #default="scope">
                <el-button link type="primary" @click="handleEdit(scope.row)" size="small">查看实体类</el-button>
                <el-button link type="primary"
                    v-if="query.Id == 0 && !['DBConfig', 'RouteConfig','User','Log'].includes(scope.row.Name)"
                    @click="onGenerateCURD(scope.row)" size="small">生成CURD页面</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-dialog title="Code Snippet" v-model="codeDialogVisible" width="50%">
        <!-- <pre class="language-csharp">{{ code }}</pre> -->
        <pre class="language-csharp line-numbers"><code>{{ code }}</code></pre>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, nextTick, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import Prism from 'prismjs';
import api from '../api'

// import fs from 'fs'
// // 文本内容
// const text = '这是要写入文件的内容';
// // 创建文件并写入内容
// fs.writeFile('example.txt', text, (err) => {
//     if (err) throw err;
//     console.log('文件已创建！');
// });
var isLoading = ref(false)
var query = reactive({
    Id: 0,
    TableName: '',
    TableDescription: ''
})
var tableData = ref([])

var codeDialogVisible = ref(false)
// var code = ref('     public Int32 code { get; set; }   ')

var code = ` `

var dbOptions = ref([])

var bgcolumnNames = [{
    Name: '表名'
}]
onMounted(async () => {
    try {
        const res = await api.post('DBConfig/GetAllDb')
        console.log('GetAllDb', res)
        dbOptions.value = res.Data // 使用 .value 来更新 ref 的值

        // 如果路由参数中没有Id，则尝试从缓存中获取
        query.Id = parseInt(localStorage.getItem('cachedId') || dbOptions.value[0].Id);


        Prism.highlightAll();
        onGetTables()
        // 使用获取的数据
    } catch (error) {
        console.error('API Error:', error);
    }
});

const onGenerateCURD = async item => {
    console.log('curd', item)
    var res = await api.post('GenerageCode/GeApiAndFront', { TableName: item.Name });
    console.log('res', res)

    if (res.Code == 200) {
        if (res.Data.isExist) {
            // 弹窗确认
            ElMessageBox.confirm(
                `${res.Message}`,
                '提示',
                {
                    confirmButtonText: '是',
                    cancelButtonText: '否',
                    type: 'warning',
                }
            ).then(async () => {
                // 用户选择是，强制覆盖
                var res2 = await api.post('GenerageCode/GeApiAndFront', { TableName: item.Name, IsForce: true });
                if (res2.Code == 200) {
                    ElMessage.success("覆盖生成成功")
                }
            });

        } else {
            ElMessage.success("生成成功")
        }
    } 
}
const handleEdit = async item => {
    console.log('sssseee', item)
    query.TableName = item.Name
    query.TableDescription = item.Description
    var res = await api.post('DBConfig/GetModelClass', query);
    codeDialogVisible.value = true
    code = res.Data
    await nextTick();

    // setTimeout(() => {

    // }, 2000);

    Prism.highlightAll();


    // Prism.highlightAll();

}

const onDbSelectChange = () => {
    localStorage.setItem('cachedId', query.Id.toString());
    onGetTables()
}

// var label=['']
var editItem = reactive({});

//获取表
const onGetTables = async () => {
    tableData.value = []
    isLoading.value = true
    const res = await api.post('DBConfig/GetDbTables', query)
    isLoading.value = false
    tableData.value = res.Data
}

</script>

<style>
.el-input {
    margin: 0 5px;
}

.CodeMirror {
    margin-right: 100px;
}

.CodeMirror-sizer {
    min-width: 500px !important;
}

.el-dialog__body {
    overflow: auto;
    max-height: 500px;
}
</style>